package com.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.PageResult;
import com.mall.common.R;
import com.mall.entity.SmoothMallCategory;
import com.mall.entity.dto.SmoothMallCategoryDto;
import com.mall.entity.dto.TreeDto;
import com.mall.service.SmoothMallCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class SmoothMallCategoryController {
    @Autowired
    SmoothMallCategoryService smoothMallCategoryService;
    //添加分类
    @PostMapping("/admin/category/add")
    @PreAuthorize("@maxAnger.hasAuthority('admin')")
    public R add(@RequestBody @Validated SmoothMallCategory smoothMallCategory){
        SmoothMallCategory one = smoothMallCategoryService.getOne(new LambdaQueryWrapper<SmoothMallCategory>()
                .eq(SmoothMallCategory::getName, smoothMallCategory.getName())
                .eq(SmoothMallCategory::getType, smoothMallCategory.getType()));
        if (one!=null){
            return R.error("该级目录已有该分类");
        }
        boolean save = smoothMallCategoryService.save(smoothMallCategory);
        if (save){
            return R.success("yes");
        }
        return R.error("添加失败");
    }
    //更新分类
    @PostMapping("/admin/category/update")
    public R update(@RequestBody @Validated SmoothMallCategory smoothMallCategory){
        boolean save = smoothMallCategoryService.saveOrUpdate(smoothMallCategory);
        if (save){
            return R.success("yes！");
        }
        return R.error("更新失败");
    }
    //删除分类
    @DeleteMapping("/admin/category/delete/{id}")
    public R update(@PathVariable Long id){
        boolean save = smoothMallCategoryService.removeById(id);
        if (save){
            return R.success("删除成功！");
        }
        return R.error("删除失败");
    }

    //获得分类列表
    @GetMapping("admin/category/list/{pageNum}/{pageSize}")
    @PreAuthorize("hasAuthority('admin')")
    public PageResult<SmoothMallCategory> adminList(@PathVariable int pageNum, @PathVariable int pageSize){
        Page pageInfo = new Page(pageNum, pageSize);
        Page page = smoothMallCategoryService.page(pageInfo);
        PageResult<SmoothMallCategory> smoothMallCategoryPageResult = new PageResult<>();
        List<SmoothMallCategory> records = pageInfo.getRecords();
        records.remove(0);
        //获取分类列表后将根节点信息去除
        smoothMallCategoryPageResult.setTotalCount(records.size()-1);
        smoothMallCategoryPageResult.setRows(records);
        return smoothMallCategoryPageResult;
    }
    //获得一级分类列表
//    @GetMapping("admin/category/list/one/{pageNum}/{pageSize}")
//    public PageResult<SmoothMallCategory> adminListOne(@PathVariable int pageNum, @PathVariable int pageSize){
//        Page pageInfo = new Page(pageNum, pageSize);
//        Page page = smoothMallCategoryService.page(pageInfo);
//        PageResult<SmoothMallCategory> smoothMallCategoryPageResult = new PageResult<>();
//        List<SmoothMallCategory> records = pageInfo.getRecords();
//        records.remove(0);
//        pageInfo.setRecords(records);
//        //获取分类列表后将根节点信息去除
//        smoothMallCategoryPageResult.setTotalCount((int) (pageInfo.getTotal()-1));
//        smoothMallCategoryPageResult.setRows(records);
//        return smoothMallCategoryPageResult;
//    }
    //获取目录级别的分类列表
    @GetMapping("/category/list")
    public List<SmoothMallCategoryDto> list(){
        List<SmoothMallCategoryDto> smoothMallCategoryDtos = smoothMallCategoryService.listDto(0);
        Map<Integer, SmoothMallCategoryDto> treeMap = smoothMallCategoryDtos.stream()
                .collect(Collectors.toMap(key -> key.getId(), value -> value));
        if (smoothMallCategoryDtos==null){
            return null;
        }
        return smoothMallCategoryDtos;
    }
    //获取树形级别的分类列表
    @GetMapping("/category/treeList")
    public List<TreeDto> treeList(){
        List<SmoothMallCategoryDto> smoothMallCategoryDtos = smoothMallCategoryService.listDto(0);
        Map<Integer, SmoothMallCategoryDto> treeMap = smoothMallCategoryDtos.stream()
                .collect(Collectors.toMap(key -> key.getId(), value -> value));
        //数型方法
        List<TreeDto> treeDtoList=new ArrayList<TreeDto>();
        smoothMallCategoryDtos.stream().forEach(item->{
            if (item.getParentId().equals(0)){
                TreeDto treeDto = new TreeDto();
                treeDto.setLabel(item.getName());
                //判断是否有子节点
                haveChildNode(item, treeDto);
                treeDtoList.add(treeDto);
            }
        });
        //树形方法
        return treeDtoList;
    }
    //判断是否有子节点
    private void haveChildNode(SmoothMallCategoryDto item, TreeDto treeDto) {
        if (item.getChildCategory() != null) {
            //是否创建了树形子节点集合，没有则创建
            if (treeDto.getChildren() == null) {
                treeDto.setChildren(new ArrayList<TreeDto>());
            }
            //构造子节点对象
            List<SmoothMallCategoryDto> childCategory = item.getChildCategory();
            childCategory.stream().forEach(item2 -> {
                TreeDto treeDto1 = new TreeDto();
                treeDto1.setLabel(item2.getName());
                haveChildNode(item2,treeDto1);
                treeDto.getChildren().add(treeDto1);
            });
        }
    }
}
